<template>
	<view class="" style="height: 100%">
		<scroll-view scroll-y="true" class="scroll-Y" :refresher-triggered="triggered" refresher-background="#f4f7f8"
			:refresher-threshold="100" @scrolltolower="onPulling" refresher-enabled="true" @refresherrefresh="onRefresh"
			refresher-default-style="black">
			<view class="carditem" v-for="(item, key) in list" :key="key" @click="itemtap(item)">
				<view class="ddh u-flex u-flex-between">
					<view class="u-line-1" style="flex: 1;">{{$z.$t("订单编号")}}：{{ item.ddh }}</view>
					<u-button type="primary" v-if="item.b_zf == 1" text="已完成" style="width: auto; margin: 0"
						size="mini"></u-button>
					<u-button type="error" v-else text="未支付" style="width: auto; margin: 0" size="mini"></u-button>
				</view>
				<view class="sj u-flex u-flex-start">
					<view>{{$z.$t("开始时间")}}：</view>
					<view>{{item.sjs}}</view>

				</view>
				<view class="sj u-flex u-flex-start">
					<view>{{$z.$t("结束时间")}}：</view>
					<view>{{item.sje ? item.sje : '-'}}</view>

				</view>
				<view class="sj u-flex u-flex-start">
					<view>{{$z.$t("站点名称")}}：</view>
					<view>{{ item.pcsmc }}</view>
				</view>
				<view class="sj u-flex u-flex-start">
					<view>{{$z.$t("占位费")}}：</view>
					<view>{{item.jesj / 100 ? item.jesj / 100 : 0}}元</view>
				</view>
			</view>
			<u-loadmore :status="status" marginBottom="30" />

		</scroll-view>
	</view>
</template>

<script>
	import qs from "qs"
	export default {
		components: {},
		props: {
			seardata: {
				typeof: Object,
				default: () => {
					return {}
				}
			}
		},
		data() {
			return {
				status: "loadmore",
				triggered: false,
				list: [],
				chargeTimes: {}, // 用于存储充电时间
				ddh: '' //充电的ddh订单号
			};
		},
		computed: {
			reqdata() {
				let r = {
					sjs: `${this.$z.timefn.gettime(360)} 00:00:00`,
					sje: `${this.$z.timefn.gettime("-1")} 00:00:00`,
				};
				r.csta = this.list.length;
				r.cmax = 10;
				// r.uUser = this.$store.state.user.USearch.uUser
				// sjs	输入	开始时间;格式 YYYY-MM-DD HH-MM-SS
				// sje	输入	结束时间;格式 YYYY-MM-DD HH-MM-SS
				return r;
			},
		},
		mounted() {
			console.log(1541541);
		},
		methods: {
			async getchargeTime(val) {
				// let reqdata = {
				// 	...this.reqdata,
				// }
				let GetRfCD = await this.$z.request("/GetRfCD", {
					ddh: val.ddh
				});
				const res = GetRfCD.length > 0 ? GetRfCD[0].cdsj : ''
				return res
			},
			async fetchChargeTimes() {
				for (const item of this.list) {
					if (item.b_zf == 0) {
						const chargeTime = await this.searchChargeTime(item);
						this.$set(this.chargeTimes, item.ddh, chargeTime);
					}
				}
			},
			async searchChargeTime(val) {
				let ChargeUserDsToUser = await this.$z.request("/ChargeUserDsToUser", {
					ddhds: val.ddh
				});
				if (ChargeUserDsToUser.length > 0) {
					let GetRfCD = await this.$z.request("/GetRfCD", {
						ddh: ChargeUserDsToUser[0].ddh
					});
					if (GetRfCD.length > 0) {
						return GetRfCD[0].sjcds;
					} else {
						return '-';
					}
				}
			},
			async onPulling() {
				if (this.status == "loading") {
					return;
				}
				this.status = "loading";
				await this.getdata()
			},
			async onRefresh() {
				if (this.status == "loading") {
					return;
				}
				this.status = "loading";
				console.log("onRefresh");
				this.triggered = true;
				this.list = [];

				await this.getdata()
				this.triggered = false;
			},
			async getdata() {
				if (!this.$store.state.user.USearch.uUser) {
					await this.$store.dispatch("user/getuser");
				}
				let USearch = this.$store.state.user.USearch;
				let reqdata = {
					...this.reqdata,
					uUser: USearch.uUser
				}
				// 1. 获取原始订单数据
				const ChargeUserDs = await this.$z.request("/ChargeUserDs", reqdata);

				// 2. 仅处理未结束的订单（b_end != 1）
				// for (const item of ChargeUserDs) {
				// 	if (item.b_end == 0) { // 只有未结束的订单需要计算
				// 		await this.updateParkingFee(item); // 更新费用
				// 	}
				// 	// b_end == 1 的订单直接跳过（保留原始数据）
				// }
				this.list = this.list.concat(ChargeUserDs);
				this.status =
					ChargeUserDs.length >= this.reqdata.cmax ? "loadmore" : "nomore";
				await this.fetchChargeTimes(); // 获取充电时间
			},

			async updateParkingFee(item) {
				// 计算当前时长（分钟）
				const durationMinutes = this.calculateDuration(item.sjs);

				// 获取费用规则参数
				const freeMinutes = item.jebd || 0; // 免费时长（分钟）
				const unitMinutes = item.dfsj || 30; // 计费单位时长（默认30分钟）
				const unitFee = item.qbf || 0; // 单位费用（分）

				// 计算超时时长和费用
				let overtimeMinutes = Math.max(0, durationMinutes - freeMinutes);
				let fee = 0;

				if (overtimeMinutes > 0) {
					const chargeUnits = Math.ceil(overtimeMinutes / unitMinutes);
					fee = chargeUnits * unitFee;
				}
				// 直接修改 item 对象
				item.je = fee > item.df ? item.df : fee; // 当前费用（分）
				console.log('item', item, fee);
			},
			calculateDuration(startTimeStr) {
				const start = new Date(startTimeStr);
				const now = new Date();
				return Math.floor((now - start) / (1000 * 60)); // 转为分钟
			},
			// 格式化时长显示（xx小时xx分钟）
			formatDuration(minutes) {
				if (minutes < 60) return `${minutes}分钟`;
				const hours = Math.floor(minutes / 60);
				const mins = minutes % 60;
				return `${hours}小时${mins}分钟`;
			},
			// 格式化费用显示（分转元）
			formatFee(fen) {
				return (fen / 100);
			},
			itemtap(item) {
				console.log('item', item);
				uni.navigateTo({
					url: `/pages/order/components/components/placeholderOrderInfo?ddh=${item.ddh}`
				})
			},

		},
	};
</script>

<style lang="scss">
	.scroll-Y {
		height: 100%;
	}

	.carditem {
		background: #fff;
		margin: 30rpx;
		border-radius: 10rpx;

		.ddh {
			height: 100rpx;
			font-size: 30rpx;
			// position: relative;
			padding: 0 30rpx;

			&::after {
				content: "";
				position: absolute;
				left: 30rpx;
				bottom: 0;
				height: 1rpx;
				background: #e5e5e5;
				right: 30rpx;
			}
		}

		.sj {
			height: 80rpx;
			font-size: 28rpx;
			// position: relative;
			padding: 0 30rpx;

			&::after {
				content: "";
				position: absolute;
				left: 30rpx;
				bottom: 0;
				height: 1rpx;
				background: #e5e5e5;
				right: 30rpx;
			}
		}

		.je {
			height: 120rpx;
			justify-content: flex-end;
			padding: 0 30rpx;
			font-size: 24rpx;

			.text {
				font-size: 36rpx;
				font-weight: bold;
				color: #2093f5;
			}
		}
	}
</style>